import React from 'react';
import { DragSource } from 'react-dnd';
import Zcon from '@cbd/icon';
import ItemTypes from './ItemTypes';
import { getUuid } from '../../../../utils/comm';
import styles from './FormSelectItem.less';

const boxSource = {
  beginDrag(props) {
    const { dropList = [], item = {} } = props;
    const { type } = item;
    const id = getUuid();
    const originalIndex = dropList.length;
    props.changeAddStatus(true);
    const nameFilter = dropList.filter(citems => citems.type === item.type);
    let code = type;
    if (type === 'integer' || type === 'type') {
      code = 'number';
    }
    return {
      ...item,
      id: `${code}_${id}`,
      originalIndex,
      name: `${item.name}${nameFilter.length + 1}`,
      code: `${code}${(new Date()).getTime()}`,
      // type: item.type,
    };
  },
  endDrag(props, monitor) {
    const didDrop = monitor.didDrop();
    if (!didDrop) {
      props.handleDelItem(monitor.getItem());
    }
  },
};

@DragSource(
  ItemTypes.BOX,
  boxSource,
  (connect, monitor) => ({
    connectDragSource: connect.dragSource(),
    isDragging: monitor.isDragging(),
    connectDragPreview: connect.dragPreview(),
  }),
)
export default class FormSelectItem extends React.Component {
  render() {
    const { isDragging, connectDragSource, connectDragPreview } = this.props;
    const { item = {}, className } = this.props;
    const opacity = isDragging ? 0.4 : 1;
    return (
      connectDragSource &&
      connectDragSource(
        <div className={className} style={{ opacity }}>
          <Zcon type={item.icon} className={styles.left_f_item} />
          {connectDragPreview(
            <span className={`${styles.left_item_desc}`}>{item.name}</span>
          )}
        </div>)
    );
  }
}